/**
 * 策略管理模块
 *
 * 该模块负责运费策略的全生命周期管理，包括策略的创建、编辑、删除和查询。
 * 支持多种计费模式（首重续重模式、重量区间模式）和策略状态管理。
 *
 * 主要功能：
 * - 策略查询和筛选（支持按名称、计费模式、状态筛选）
 * - 策略创建和编辑（支持丰富的表单验证）
 * - 策略状态管理（启用/禁用）
 * - 策略搜索和选择器功能（支持防抖搜索）
 * - 强制刷新机制（解决Vue响应式更新问题）
 *
 * API调用统一管理：
 * - 查询：api.getStrategies() -> GET /strategy/list
 * - 新增：api.addStrategy() -> POST /strategy/add
 * - 更新：api.updateStrategy() -> POST /strategy/edit
 * - 删除：api.deleteStrategy() -> POST /strategy/delete
 *
 * @author 运费系统团队
 * @version 2.1.0
 * @since 2025-08-29
 * @requires api.js - 统一API服务管理
 */

function useStrategyManagement() {
    const { ref, reactive, computed, nextTick } = Vue;
    // 响应式数据
    const strategies = ref([]);
    const submitting = ref(false);
    const showAddStrategyModal = ref(false);
    const showEditStrategyModal = ref(false);
    const showCopyStrategyModal = ref(false);

    // 复制策略表单
    const copyStrategyForm = reactive({
        id: null,
        newName: '',
        description: ''
    });

    // 当前选择的策略（用于复制）
    const currentStrategyForCopy = ref(null);

    // 添加强制更新标识
    const forceUpdateFlag = ref(0);

    // 策略搜索
    const strategySearchKeyword = ref('');
    const filteredStrategies = ref([]);
    const showStrategyDropdown = ref(false);

    // 策略查询条件
    const strategyQuery = reactive({
        name: '', // 策略名称模糊查询
        pricingModel: '', // 计费模式查询
        status: '' // 状态查询
    });

    const strategyForm = reactive({
        id: null,
        name: '',
        description: '',
        pricingModel: '',
        firstWeightKg: null,
        firstWeightFee: null,
        additionalWeightKg: null,
        additionalWeightFee: null,
        volumetricWeightRatio: null,
        status: 1
    });

    // 添加计算属性来确保响应性
    const strategiesComputed = computed(() => {
        // 使用forceUpdateFlag确保重新计算
        forceUpdateFlag.value; // 触发依赖
        return strategies.value;
    });

    // 强制刷新方法
    const forceRefreshTable = () => {
        forceUpdateFlag.value++;
    };

    /**
     * 加载所有策略
     */
    const loadStrategies = async (query = null) => {
        try {
            const queryParams = query || strategyQuery;
            console.log('加载策略数据，查询参数:', queryParams);
            const result = await api.getStrategies(queryParams);

            if (result.code === 0) {
                // 总是更新数据，即使结果为空数组也要清除当前显示
                const newData = result.data || [];

                // 强制更新数组
                strategies.value.length = 0; // 先清空
                strategies.value.push(...newData); // 再添加

                // 强制触发响应式更新
                forceUpdateFlag.value++;

                console.log('加载策略成功，数量:', strategies.value.length);
            } else {
                // API失败时也要清空数据
                strategies.value = [];
                Utils.showMessage('加载策略失败: ' + result.msg, true);
            }
        } catch (err) {
            console.error('加载策略失败:', err);
            // 请求异常时也要清空数据
            strategies.value = [];
            Utils.showMessage('加载策略失败', true);
        }
    };

    /**
     * 根据关键字筛选策略
     */
    const filterStrategies = (keyword = '') => {
        if (!keyword || keyword.trim() === '') {
            filteredStrategies.value = (strategies.value || []).filter(s => s.status === 1);
        } else {
            const lowerKeyword = keyword.toLowerCase();
            filteredStrategies.value = (strategies.value || []).filter(strategy => {
                return strategy.status === 1 &&
                       strategy.name &&
                       strategy.name.toLowerCase().includes(lowerKeyword);
            });
        }
    };

    /**
     * 处理带防抖的策略搜索
     */
    let searchTimeout = null;
    const handleStrategySearch = (keyword) => {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            filterStrategies(keyword);
        }, 200);
    };

    /**
     * 根据ID获取策略名称
     */
    const getStrategyName = (strategyId) => {
        const strategy = (strategies.value || []).find(s => s.id === strategyId);
        return strategy ? strategy.name : '未知策略';
    };

    /**
     * 获取选中策略名称用于显示
     */
    const getSelectedStrategyName = (strategyId) => {
        if (!strategyId) return '';
        return getStrategyName(strategyId);
    };

    /**
     * 选择策略并更新目标字段
     */
    const selectStrategy = (strategy, targetField = 'freightForm') => {
        // Update search keyword to show selected strategy name
        strategySearchKeyword.value = strategy.name;
        showStrategyDropdown.value = false;
        filteredStrategies.value = [];

        // Return strategy ID for parent to handle
        return strategy.id;
    };

    /**
     * 显示策略下拉选项
     */
    const showStrategyOptions = (keyword = '') => {
        filterStrategies(keyword);
        showStrategyDropdown.value = true;
    };

    /**
     * 隐藏策略下拉框
     */
    const hideStrategyDropdown = () => {
        setTimeout(() => {
            showStrategyDropdown.value = false;
        }, 200);
    };

    /**
     * 重置策略搜索
     */
    const resetStrategySearch = () => {
        strategySearchKeyword.value = '';
        filteredStrategies.value = [];
        showStrategyDropdown.value = false;
    };

    /**
     * 添加新策略
     */
    const addStrategy = () => {
        resetStrategyForm();
        showAddStrategyModal.value = true;
    };

    /**
     * 编辑现有策略
     */
    const editStrategy = (strategy) => {
        // 添加安全检查
        if (!strategy || !strategy.id) {
            console.error('无效的策略数据:', strategy);
            Utils.showMessage('无效的策略数据', true);
            return;
        }

        Object.assign(strategyForm, strategy);
        showEditStrategyModal.value = true;
    };

    /**
     * 复制并新建策略
     */
    const copyAndCreateStrategy = (strategy) => {
        // 添加安全检查
        if (!strategy || !strategy.id) {
            console.error('无效的策略数据:', strategy);
            Utils.showMessage('无效的策略数据', true);
            return;
        }

        // 设置当前复制的策略
        currentStrategyForCopy.value = strategy;
        copyStrategyForm.id = strategy.id;
        copyStrategyForm.newName = `${strategy.name}_副本`;
        copyStrategyForm.description = strategy.description || '';

        // 打开复制弹框
        showCopyStrategyModal.value = true;

    };

    /**
     * 提交策略表单
     */
    const submitStrategy = async () => {
        const validation = validateStrategyForm();
        if (!validation.isValid) {
            Utils.showMessage(validation.errors[0], true);
            return;
        }

        submitting.value = true;
        try {
            // API安全检查
            console.log('🔧 提交策略数据:', strategyForm);
            console.log('🔧 API对象:', api);

            // 检查API对象是否存在
            if (!api) {
                console.error('❌ API对象未正确导入到strategy-management.js');
                throw new Error('API对象未正确初始化，请刷新页面重试');
            }

            const isUpdate = Boolean(strategyForm.id);
            const methodName = isUpdate ? 'updateStrategy' : 'addStrategy';
            const apiMethod = api[methodName];

            console.log('🔧 选择的API方法:', methodName, '是否存在:', !!apiMethod);

            if (!apiMethod || typeof apiMethod !== 'function') {
                console.error(`❌ API方法 ${methodName} 不存在或不是函数`);
                throw new Error(`API方法 ${methodName} 不存在或不是函数，请检查api.js配置`);
            }

            const result = await apiMethod(strategyForm);

            console.log('🔧 API调用结果:', result);

            if (result.code === 0) {
                Utils.showMessage('操作成功');
                closeStrategyModal();
                loadStrategies();
            } else {
                Utils.showMessage(result.msg || '操作失败', true);
            }
        } catch (err) {
            console.error('❌ 策略提交错误详情:', err);

            // 根据错误类型提供不同的错误信息
            let errorMessage = '提交失败';

            if (err.message.includes('Cannot read properties of undefined')) {
                if (err.message.includes("reading 'post'")) {
                    errorMessage = 'API对象的post方法未正确初始化，请刷新页面重试';
                } else {
                    errorMessage = 'API对象未正确初始化，请刷新页面重试';
                }
            } else if (err.message.includes('is not a function')) {
                errorMessage = 'API方法不存在，请检查系统配置';
            } else if (err.message.includes('Network Error') || err.message.includes('timeout')) {
                errorMessage = '网络连接错误，请检查网络连接后重试';
            } else {
                errorMessage = err.message || '未知错误';
            }

            Utils.showMessage(`提交失败: ${errorMessage}`, true);
        } finally {
            submitting.value = false;
        }
    };

    /**
     * 删除策略
     */
    const deleteStrategy = async (id) => {
        if (!confirm('确定要删除这个策略吗？')) return;

        try {
            const result = await api.deleteStrategy(id);
            if (result.code === 0) {
                Utils.showMessage('删除成功');
                loadStrategies();
            } else {
                Utils.showMessage(result.msg || '删除失败', true);
            }
        } catch (err) {
            Utils.showMessage(err.message, true);
        }
    };

    /**
     * 关闭策略模态框
     */
    const closeStrategyModal = () => {
        showAddStrategyModal.value = false;
        showEditStrategyModal.value = false;
        resetStrategyForm();
    };

    /**
     * 重置策略表单
     */
    const resetStrategyForm = () => {
        Object.assign(strategyForm, {
            id: null,
            name: '',
            description: '',
            pricingModel: '',
            firstWeightKg: null,
            firstWeightFee: null,
            additionalWeightKg: null,
            additionalWeightFee: null,
            volumetricWeightRatio: null,
            status: 1
        });
    };

    /**
     * 搜索策略
     */
    const searchStrategies = async () => {
        try {
            console.log('执行策略查询，查询条件:', strategyQuery);

            // 调用loadStrategies来执行实际查询
            await loadStrategies(strategyQuery);

            const resultCount = strategies.value.length;
            console.log('策略查询完成，结果数量:', resultCount);

            if (resultCount === 0) {
                Utils.showMessage('查询成功，找到 0 条记录');
                // 强制刷新表格
                forceRefreshTable();
            } else {
                Utils.showMessage(`查询成功，找到 ${resultCount} 条记录`);
            }
        } catch (err) {
            console.error('策略查询失败:', err);
            strategies.value = [];
            Utils.showMessage('查询失败', true);
        }
    };

    /**
     * 重置搜索条件
     */
    const resetStrategyQuery = async () => {
        Object.assign(strategyQuery, {
            name: '',
            pricingModel: '',
            status: ''
        });
        console.log('重置策略查询条件，重新加载所有数据');
        await loadStrategies();
        Utils.showMessage('已重置查询条件');
    };

    /**
     * 获取计费模式名称
     */
    const getPricingModelName = (pricingModel) => {
        return pricingModel === 1 ? '首重续重' : '首重续重+重量区间';
    };

    // 导出到全局作用域，供其他模块使用
    window.getPricingModelName = getPricingModelName;

    /**
     * 切换策略状态
     */
    const toggleStrategyStatus = async (strategy) => {
        // 添加安全检查
        if (!strategy || !strategy.id || strategy.status === undefined) {
            console.error('无效的策略数据:', strategy);
            Utils.showMessage('无效的策略数据', true);
            return;
        }

        const newStatus = strategy.status === 1 ? 2 : 1;
        const statusText = newStatus === 1 ? '启用' : '禁用';

        if (!confirm(`确定要${statusText}这个策略吗？`)) return;

        try {
            const updateData = { ...strategy, status: newStatus };
            const result = await api.updateStrategy(updateData);
            if (result.code === 0) {
                Utils.showMessage(`${statusText}成功`);
                loadStrategies();
            } else {
                Utils.showMessage(result.msg || `${statusText}失败`, true);
            }
        } catch (err) {
            Utils.showMessage(err.message, true);
        }
    };

    /**
     * 获取策略状态文本
     */
    const getStrategyStatusText = (status) => {
        if (status === undefined || status === null) return '-';
        return status === 1 ? '启用' : '禁用';
    };

    /**
     * 获取策略状态样式类
     */
    const getStrategyStatusClass = (status) => {
        if (status === undefined || status === null) return '';
        return status === 1 ? 'status-enabled' : 'status-disabled';
    };
    const validateStrategyForm = () => {
        const errors = [];

        if (!strategyForm.name || strategyForm.name.trim() === '') {
            errors.push('策略名称不能为空');
        }

        if (!strategyForm.pricingModel) {
            errors.push('请选择计费模式');
        }

        if (!strategyForm.firstWeightKg || strategyForm.firstWeightKg < 0) {
            errors.push('首重重量不能为负数');
        }

        if (!strategyForm.firstWeightFee || strategyForm.firstWeightFee < 0) {
            errors.push('首重费用不能为负数');
        }

        if (!strategyForm.additionalWeightKg || strategyForm.additionalWeightKg < 0) {
            errors.push('续重单位重量不能为负数');
        }

        if (!strategyForm.additionalWeightFee || strategyForm.additionalWeightFee < 0) {
            errors.push('续重单位费用不能为负数');
        }

        return {
            isValid: errors.length === 0,
            errors
        };
    };

    return {
        // State
        strategies,
        strategiesComputed, // 计算属性
        submitting,
        showAddStrategyModal,
        showEditStrategyModal,
        strategyForm,
        strategySearchKeyword,
        filteredStrategies,
        showStrategyDropdown,
        strategyQuery,
        forceUpdateFlag, // 添加强制更新标识

        // Methods
        loadStrategies,
        searchStrategies,
        resetStrategyQuery,
        filterStrategies,
        handleStrategySearch,
        getStrategyName,
        getSelectedStrategyName,
        selectStrategy,
        showStrategyOptions,
        hideStrategyDropdown,
        resetStrategySearch,
        addStrategy,
        editStrategy,
        submitStrategy,
        deleteStrategy,
        closeStrategyModal,
        resetStrategyForm,
        validateStrategyForm,
        getPricingModelName,
        toggleStrategyStatus,
        getStrategyStatusText,
        getStrategyStatusClass,

        // 复制策略相关方法
        showCopyStrategyModal,
        copyStrategyForm,
        currentStrategyForCopy,
        copyAndCreateStrategy,
        submitCopyStrategy,
        closeCopyStrategyModal
    };

    /**
     * 提交复制策略
     */
    async function submitCopyStrategy() {
        if (!copyStrategyForm.newName || copyStrategyForm.newName.trim() === '') {
            Utils.showMessage('新策略名称不能为空', true);
            return;
        }

        submitting.value = true;
        try {
            const result = await api.copyStrategyData({
                id: copyStrategyForm.id,
                newName: copyStrategyForm.newName,
                description: copyStrategyForm.description
            });

            if (result.code === 0) {
                Utils.showMessage('复制策略成功');
                closeCopyStrategyModal();
                loadStrategies();
            } else {
                Utils.showMessage(result.msg || '复制策略失败', true);
            }
        } catch (err) {
            console.error('复制策略失败:', err);
            Utils.showMessage('复制策略失败: ' + (err.message || '未知错误'), true);
        } finally {
            submitting.value = false;
        }
    }

    /**
     * 关闭复制策略弹框
     */
    function closeCopyStrategyModal() {
        showCopyStrategyModal.value = false;
        copyStrategyForm.id = null;
        copyStrategyForm.newName = '';
        copyStrategyForm.description = '';
        currentStrategyForCopy.value = null;
    }
}
